<?php

namespace app\common\business;
use app\common\lib\Show;
use app\common\model\MallMembercard;
use app\common\model\MallGoodsCard;
use app\common\validate\Goods as ValObj;
use app\common\model\MallGoods as ModelObj;
use think\Exception;
use think\facade\Log;
use think\Db;
use think\Model;

class Goods extends Base
{
    /**
     * @var ValObj
     */
    protected ValObj $valObj;
    /**
     * @var ModelObj
     */
    protected ModelObj $modelObj;

    /**
     *
     */
    public function __construct()
    {
        $this->valObj = new ValObj();
        $this->modelObj = new ModelObj();
    }




    /**
     * @param array $data
     * @param string $scene
     * @throws Exception
     */
    protected function isValidateAdd(array $data = [], string $scene = 'add')
    {
        if (!$this->valObj->check($data)) {
            throw new Exception($this->valObj->getError());
        }
    }

    /**
     * @param string $field
     * @return array
     * @throws Exception
     */
    public function getNearByGoods(array $where, string $field='*',string $lat, string $lng)
    {

        try {
            $result = $this->modelObj->getModelByListToArray($where,$field,'sort desc,id desc');

        } catch (\Exception $e) {
            throw new Exception("查询失败");
        }
        if($result){
            foreach($result as $k=>$v){
                if($lat !=0 && $lng!=0 && $v['lng']!=0 && $v['lat'] !=0){
                    $result[$k]['juli'] =Show::getDistances($lng,$lat,$v['lng'],$v['lat'],2);
                }else{
                    $result[$k]['juli'] ='...';
                }

                unset($result[$k]['lng']);
                unset($result[$k]['lat']);
            }
        }
        return $result;
    }

    public function getallGoodslistByNew(string $openid, array $where, int $page,string $field='*'){
        try{
            $result =$this->modelObj->field($field)->where($where)->order('id desc')->page($page,10)->select()->toArray();
        }catch (\Exception $e){
            throw new Exception("查询失败");
        }
        if($result){
            foreach($result as $k=>$v){
                // 此处根据会员等级计算会员价，默认给商品价格
                $cardinfo =(new MallMembercard())->alias('c')->field('c.persent,m.overtime,m.usertype')->join('mall_member m','m.usertype=c.id')->where("m.openid='$openid'")->find();
                if($cardinfo && ($cardinfo['overtime']>time())){

                    $goodscard= (new MallGoodsCard())->where([['goods_id','=',$v['id']],['card_id','=',$cardinfo['usertype']]])->find();
                    if($goodscard){
                        $result[$k]['user_price'] =$goodscard['price'];
                    }else{
                        $result[$k]['user_price'] =$v['goods_price'];
                    }
                }else{
                    $result[$k]['user_price'] =$v['goods_price'];
                }
            }
        }
        return $result;
    }


    /**
     * 获取指定的商品列表
     * @param array $where
     * @param string $field
     * @return array
     * @throws Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getallGoodslist(string $openid,array $where, string $field='*'){

        try {
            $result = $this->modelObj->getModelByListToArray($where,$field,'sort desc,id desc');

        } catch (\Exception $e) {
            throw new Exception("查询失败");
        }
        if($result){
            foreach($result as $k=>$v){
                // 此处根据会员等级计算会员价，默认给商品价格
                $cardinfo =(new MallMembercard())->alias('c')->field('c.persent,m.overtime,m.usertype')->join('mall_member m','m.usertype=c.id')->where("m.openid='$openid'")->find();
                if($cardinfo && ($cardinfo['overtime']>time())){

                    $goodscard= (new MallGoodsCard())->where([['goods_id','=',$v['id']],['card_id','=',$cardinfo['usertype']]])->find();
                    if($goodscard){
                        $result[$k]['user_price'] =$goodscard['price'];
                    }else{
                        $result[$k]['user_price'] =$v['goods_price'];
                    }
                }else{
                    $result[$k]['user_price'] =$v['goods_price'];
                }
            }
        }
        return $result;
    }



    /**
     *  根据购物车id查询商品信息
     */
    public function getGoodsInfoByCartId(string $openid,int $cart_id){
        try{

          $goods= $this->modelObj->alias('g')->field('g.*')->join("mall_cart c",'c.goodsid=g.id')->where("c.id='$cart_id'")->find();

        }catch (\Exception $e){
            throw new Exception("查询失败");
        }

        return $goods;
    }


    /**
     * @param array $where
     * @param string $field
     * @return array|\think\Model|null
     * @throws Exception
     */
    public function  getGoodsInfo(string $openid,array $where,string $field='*'){

        try {
            $result = $this->modelObj->getModelByInfo($where,$field);
        } catch (\Exception $e) {
            throw new Exception("查询失败");
        }

        if($result){
            // 此处根据会员等级计算会员价，默认给商品价格
            $cardinfo =(new MallMembercard())->alias('c')->field('c.persent,m.overtime,m.usertype')->join('mall_member m','m.usertype=c.id')->where("m.openid='$openid'")->find();
            if($cardinfo && ($cardinfo['overtime']>time())){
                //$result['user_price'] =round($result['goods_price']*$cardinfo['persent']/100,2);
                $goodscard= (new MallGoodsCard())->where([['goods_id','=',$result['id']],['card_id','=',$cardinfo['usertype']]])->find();

                if($goodscard){
                    $result['user_price'] =$goodscard['price'];
                }else{
                    $result['user_price'] =$result['goods_price'];
                }
            }else{
                $result['user_price'] =$result['goods_price'];
            }
            $result['description'] =htmlspecialchars_decode($result['description']);
            if($result['images']){
                $goodsimages =explode('|',$result['images']);
            }else{
                $goodsimages =[];
            }
            $result['images'] =$goodsimages;
        }else{
            $result=[];
        }
        return $result;
    }

    /**
     * 商品审核记录
     * @param $openid
     * @return mixed
     * @throws Exception
     */
    public function getManagerByGoods($openid){

        try{
            $list= $this->modelObj->alias('g')->field('g.id,g.create_time,g.apply_status,g.mendian,g.title,g.apply_reason')->join('mall_manager m','m.id=g.manager_id')
                ->where("m.openid='".$openid."'")
                ->order('g.create_time desc')
                ->select()
                ->toArray();
        }catch (\Exception $e){
            throw new Exception("查询失败");
        }

        if($list){
            foreach ($list as $kl=>$v){
                $mendian=json_decode($v['mendian'],true);
                $list[$kl]['store_name'] =$mendian[0]['store_name']??'';
                $list[$kl]['store_mobile'] =$mendian[0]['store_mobile']??'';
            }
        }
        return $list;
    }



    /**
     * 编辑商品信息
     * @param $data
     * @return bool
     * @throws Exception
     */
    public function saveData($data){
        //验证字段
        $this->isValidateAdd($data);
        try{
            $info =$this->modelObj->getModelByInfo([['id','=',$data['id']]],'*');
        }catch (\Exception $e){
            throw new Exception($e->getMessage());
        }
        if($info){
            $info->save($data);
        }else{
            $this->modelObj->save($data);
        }
        return true;
    }
}